﻿//对js对象的扩展　开始

/**   
* 对Date的扩展，将 Date 转化为指定格式的String   
* 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q) 可以用 1-2 个占位符   
* 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)   
* eg:   
* (new Date()).pattern("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423   
* (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04   
* (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04   
* (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04   
* (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18   
*/
Date.prototype.pattern = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份     
        "d+": this.getDate(), //日     
        "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时     
        "H+": this.getHours(), //小时     
        "m+": this.getMinutes(), //分     
        "s+": this.getSeconds(), //秒     
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度     
        "S": this.getMilliseconds() //毫秒     
    };
    var week = {
        "0": "\u65e5",
        "1": "\u4e00",
        "2": "\u4e8c",
        "3": "\u4e09",
        "4": "\u56db",
        "5": "\u4e94",
        "6": "\u516d"
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468") : "") + week[this.getDay() + ""]);
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}
Date.prototype.addYears = function (value) {
    this.setFullYear(this.getFullYear() + value);
    return this;
}
Date.prototype.addHours = function (value) {
    this.setHours(this.getHours() + value);
    return this;
}
Date.prototype.addDays = function (value) {
    this.addHours(24 * value);
    return this;
}
Date.prototype.addMonths = function (value) {
    this.setMonth(this.getMonth() + value);
    return this;
}
Date.prototype.toDate = function () {
    return this;
}
String.prototype.toDate = function () {
    //将字符串转换为日期 
    if (this.indexOf("Date(") > 0) {
        var str = this.substr(this.indexOf("(") + 1);
        var str = str.substr(0, str.indexOf("+"));
        return new Date(Number(str));
    }
    return new Date(Date.parse(this.replace(/-/g, "/")));
}
String.prototype.htmlEncode = function () {
    var s = this;
    s = s.replace(/&/g, "&amp;");
    s = s.replace(/</g, "&lt;");
    s = s.replace(/>/g, "&gt;");
    //s = s.replace(/ /g, "&nbsp;");
    s = s.replace(/'/g, "&apos;");
    s = s.replace(/\"/g, "&quot;");
    return s;
}
String.prototype.htmlDecode = function () {
    var s = this;
    s = str.replace(/&amp;/g, "&");
    s = s.replace(/&lt;/g, "<");
    s = s.replace(/&gt;/g, ">");
    //s = s.replace(/&nbsp;/g, " ");
    s = s.replace(/&#39;/g, "\'");
    s = s.replace(/&quot;/g, "\"");
    return s;
}

//数据中是否包括指定对象
Array.prototype.contain = function (fun) {
    for (var item in this) {
        if (fun.constructor == Function) {
            if (fun(item) == true) return true;
        }
    }
    return false;
}
Array.prototype.get = function (fun) {
    for (var i in this) {
        if (fun.constructor == Function) {
            if (fun(this[i]) == true) return this[i];
        }
    }
    return null;
}
Array.prototype.del = function (n) {//n表示第几项，从0开始算起。
    //prototype为对象原型，注意这里为对象增加自定义方法的方法。
    if (n > this.length - 1) return false;
    if (n < 0)//如果n<0，则不进行任何操作。
        return this;
    else
        return this.slice(0, n).concat(this.slice(n + 1, this.length));
    /*
　　　concat方法：返回一个新数组，这个新数组是由两个或更多数组组合而成的。
　　　　　　　　　这里就是返回this.slice(0,n)/this.slice(n+1,this.length)
　　 　　　　　　组成的新数组，这中间，刚好少了第n项。
　　　slice方法： 返回一个数组的一段，两个参数，分别指定开始和结束的位置。
　　*/
}
//对js对象的扩展　结束


function stopDefault(e) {
    //阻止默认浏览器动作(W3C) 
    if (e && e.preventDefault)
        e.preventDefault();
    //IE中阻止函数器默认动作的方式 
    else
        window.event.returnValue = false;
    return false;
}

function stopBubble(e) {
    //如果提供了事件对象，则这是一个非IE浏览器 
    if (e && e.stopPropagation)
    //因此它支持W3C的stopPropagation()方法 
        e.stopPropagation();
    else
    //否则，我们需要使用IE的方式来取消事件冒泡 
        window.event.cancelBubble = true;
}

//对命名空间，方法名称以及参数名称的命名未按照规范命名
var DaAn = {};


//字符串 
DaAn.String = {
    Trim: function (str) { },
    Remove: function (str, startIndex, count) { },
    Replace: function (str, oldChar, newChar) { },
    Contain: function (str, value) {
        return str.toLowerCase().indexOf(value) > -1;
    }
}


//http
DaAn.Http = {
    AddRandomNumber: function (url) {
        //为url添加随机数
        return url + "&r=" + Math.random();
    },
    Open: function (url) {
        window.open(url);
    },
    Redirect: function (url) {
        //跳转页面
        window.location.href = url;
    },
    GetCookie: function (name) {
        //获取cookie
        var cookie_start = document.cookie.indexOf(name);
        var cookie_end = document.cookie.indexOf(";", cookie_start);
        return cookie_start == -1 ? '' : unescape(document.cookie.substring(cookie_start + name.length + 1, (cookie_end > cookie_start ? cookie_end : document.cookie.length)));
    },
    SetCookie: function (cookieName, cookieValue, seconds, path, domain, secure) {
        //设置cookie
        var expires = new Date();
        expires.setTime(expires.getTime() + seconds);
        document.cookie = escape(cookieName) + '=' + escape(cookieValue)
        + (expires ? '; expires=' + expires.toGMTString() : '')
        + (path ? '; path=' + path : '/')
        + (domain ? '; domain=' + domain : '')
        + (secure ? '; secure' : '');
    },
    RemoveCookie: function (cookieName) {
        //除移cookie
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        document.cookie = cookieName + "= ;expires=" + exp.toGMTString();
    },
    GetUrlParam: function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null)
            return unescape(r[2]);
        return null;
    }
}

//对话框
DaAn.Dialog = {
    Alert: function (msg, callback) {
        //弹出提示对话框
        window.art.dialog({
            title: '消息',
            content: msg,
            width: 320,
            ok: callback
        });

    },
    Open: function (url, options, cache) {
        window.art.dialog.open(url, options, cache);
    }
}

//延迟执执函数 不允许对二个函数执行延迟执行
DaAn.DelayExecute = function (code, time) {
    if (!DaAn.delayVar) DaAn.delayVar = "";
    window.clearTimeout(DaAn.delayVar);
    DaAn.delayVar = setTimeout(code, time);
}
//将josn字符串反序列化为js对象
DaAn.Deserialize = function (json) {
    return jQuery.parseJSON(json)
}

//ajax
DaAn.Ajax = function (url, data, callback, cfg) {
    if (!cfg) cfg = {};
    if (cfg.hasOwnProperty("async") == false) cfg.async = "true";
    if (cfg.hasOwnProperty("type") == false) cfg.type = "get";
    if (cfg.hasOwnProperty("cache") == false) cfg.cache = true;
    $.ajax({
        type: cfg.type,
        url: url,
        async: cfg.async,
        data: data,
        cache: cfg.cache,
        timeout: 30000,
        beforeSend: cfg.hasOwnProperty("before") == false ? function () { } : cfg.before,
//        complete: function () { alert('请求完成'); },
        success: callback,
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //            DaAn.Dialog.Alert("ajax get error:" + XMLHttpRequest.responseText);
        }
    });
}


//模板相关操作
DaAn.Template = {
    ProcessTemplate: function (args) {
        //args 示例 {name:"",data:{},callback:function(){}}
        if (DaAn.String.Contain(args.name, ".") == false) args.name = args.name + ".html";
        var url = "/Template/" + args.name;
        DaAn.Ajax.Get(url, {}, function (html) {
            args.callback(html);
        });
    }
}

//html控件相关
DaAn.Control = {
    SetRadioCheckedItem: function (name, value) {
        $(":radio[name='" + name + "'][value='" + value + "']").attr("checked", true);
    },
    SetSelectCheckedItem: function (id, value) {
        $("#" + id).val(value);
    },
    SelectBind: function (selectID, datas, param, defaultItem) {
        //datas 下拉列表框绑定数据 
        //param 格式{text:"绑字的文本属性名",value:"绑定的值属性名"}
        //defaultItem 默认项 格式{text:"--请选择--",value:"-1"}
        if (datas.constructor != Array) {
            alert("SelectBind 的参数 datas 必需为一个数组");
            return
        }
        var html = "";
        if (defaultItem.constructor == Object)
            html = html + "<option selected value='" + defaultItem.value + "'>" + defaultItem.text + "</option>";
        for (var i = 0; i < datas.length; i++) {
            html = html + "<option value='" + datas[i][param.value] + "'>" + datas[i][param.text] + "</option>";

        }
        $("#" + selectID).html(html);
    }
}




//DaAn.Tip =  function (options) {
//    if (options.hasOwnProperty("type")) {
//        if (options.type == "error") {
//            options.content = "<span class=\"upbox-uniline colorRed\"><em class=\"error-icon margin-r10\"></em>" + options.content + "</span>";
//        } else {
//            options.content = "<span  class=\"upbox-uniline round colorGreen\"><em class=\"correct-icon margin-r10\"></em>" + options.content + "</span>";
//        }
//    }
//    return _proxyDialog({
//        id: 'Tips',
//        zIndex: _zIndex(),
//        title: false,
//        cancel: false,
//        fixed: true,
//        lock: options.hasOwnProperty("lock") == true ? true : false
//    })
//	.content('<div>' + options.content + '</div>')
//	.time(options.time || 1.5);
//};




DaAn.Regexp = {
    //email的判断
    Ismail: function (mail) {
        return (new RegExp(/^\w+((-\w+)|(\.\w+))*\-AT-[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/).test(mail));
    },
    //身份证的验证
    //    IsIdCardNo: function (num) {
    //        if (isNaN(num)) { return false; }
    //        var len = num.length, re;
    //        if (len == 15)
    //            re = new RegExp(/^(\d{6})()?(\d{2})(\d{2})(\d{2})(\d{3})$/);
    //        else if (len == 18)
    //            re = new RegExp(/^(\d{6})()?(\d{4})(\d{2})(\d{2})(\d{3})(\d)$/);
    //        else { return false; }
    //        var a = num.match(re);
    //        if (a != null) {
    //            if (len == 15) {
    //                var D = new Date("19" + a[3] + "/" + a[4] + "/" + a[5]);
    //                var B = D.getYear() == a[3] && (D.getMonth() + 1) == a[4] && D.getDate() == a[5];
    //            }
    //            else {
    //                var D = new Date(a[3] + "/" + a[4] + "/" + a[5]);
    //                var B = D.getFullYear() == a[3] && (D.getMonth() + 1) == a[4] && D.getDate() == a[5];
    //            }
    //            if (!B) { return false; }
    //        }
    //        return true;
    //    },

    IsIdCardNo:function (num) {
         var factorArr = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1);
         var error;
         var varArray = new Array();  
         var intValue;
         var lngProduct = 0;
         var intCheckDigit;
         var intStrLen = num.length;
         var idNumber = num;
         if ((intStrLen != 15) && (intStrLen != 18)) {
             return false;
         }
         for (i = 0; i < intStrLen; i++) {
             varArray[i] = idNumber.charAt(i);
             if ((varArray[i] < '0' || varArray[i] > '9') && (i != 17)) {
                 return false;
             } else if (i < 17) {
                 varArray[i] = varArray[i] * factorArr[i];
             }
         }
         if (intStrLen == 18) {
             var date8 = idNumber.substring(6, 14);
             if (checkDate(date8) == false) {
                 return false;
             }
             for (i = 0; i < 17; i++) {
                 lngProduct = lngProduct + varArray[i];
             }
             intCheckDigit = 12 - lngProduct % 11;
             switch (intCheckDigit) {
                 case 10:
                     intCheckDigit = 'X';
                     break;
                 case 11:
                     intCheckDigit = 0;
                     break;
                 case 12:
                     intCheckDigit = 1;
                     break;
             }
             if (varArray[17].toUpperCase() != intCheckDigit) {
                 return false;
             }
         }
         else {
             var date6 = idNumber.substring(6, 12);
             if (checkDate(date6) == false) {
                 return false;
             }
         }
         return true;
     },
//    IsIdCardNo: function (idcard) {
//        var Errors = new Array(
//"验证通过!",
//"身份证号码位数不对!",
//"身份证号码出生日期超出范围或含有非法字符!",
//"请输入真实的身份证号!",
//"身份证地区非法!"
//);
//        var area = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外" }

//        var idcard, Y, JYM;
//        var S, M;
//        var idcard_array = new Array();
//        idcard_array = idcard.split("");
//        //地区检验
//        if (area[parseInt(idcard.substr(0, 2))] == null) return Errors[4];
//        //身份号码位数及格式检验
//        switch (idcard.length) {
//            case 15:
//                if ((parseInt(idcard.substr(6, 2)) + 1900) % 4 == 0 || ((parseInt(idcard.substr(6, 2)) + 1900) % 100 == 0 && (parseInt(idcard.substr(6, 2)) + 1900) % 4 == 0)) {
//                    ereg = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$/; //测试出生日期的合法性
//                } else {
//                    ereg = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$/; //测试出生日期的合法性
//                }
//                if (ereg.test(idcard)) return Errors[0];
//                else return Errors[2];
//                break;
//            case 18:
//                //18位身份号码检测
//                //出生日期的合法性检查
//                //闰年月日:((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))
//                //平年月日:((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))
//                if (parseInt(idcard.substr(6, 4)) % 4 == 0 || (parseInt(idcard.substr(6, 4)) % 100 == 0 && parseInt(idcard.substr(6, 4)) % 4 == 0)) {
//                    ereg = /^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$/; //闰年出生日期的合法性正则表达式
//                } else {
//                    ereg = /^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$/; //平年出生日期的合法性正则表达式
//                }
//                if (ereg.test(idcard)) {//测试出生日期的合法性
//                    //计算校验位
//                    S = (parseInt(idcard_array[0]) + parseInt(idcard_array[10])) * 7
//+ (parseInt(idcard_array[1]) + parseInt(idcard_array[11])) * 9
//+ (parseInt(idcard_array[2]) + parseInt(idcard_array[12])) * 10
//+ (parseInt(idcard_array[3]) + parseInt(idcard_array[13])) * 5
//+ (parseInt(idcard_array[4]) + parseInt(idcard_array[14])) * 8
//+ (parseInt(idcard_array[5]) + parseInt(idcard_array[15])) * 4
//+ (parseInt(idcard_array[6]) + parseInt(idcard_array[16])) * 2
//+ parseInt(idcard_array[7]) * 1
//+ parseInt(idcard_array[8]) * 6
//+ parseInt(idcard_array[9]) * 3;
//                    Y = S % 11;
//                    M = "F";
//                    JYM = "10X98765432";
//                    M = JYM.substr(Y, 1); //判断校验位
//                    if (M == idcard_array[17]) return Errors[0]; //检测ID的校验位
//                    else return Errors[3];
//                }
//                else return Errors[2];
//                break;
//            default:
//                return Errors[1];
//                break;
//        }

//    },
    //验证ＩＰ地址
    Isip: function (s) {
        var check = function (v) { try { return (v = 0) } catch (x) { return false } };
        var re = s.split(".")
        return (re.length == 4) ? (check(re[0]) && check(re[1]) && check(re[2]) && check(re[3])) : false
    },
    //校验密码：只能输入6-15个字母、数字
    IsPasswd: function (s) {
        var patrn = /^[a-zA-Z0-9]{6,15}$/;
        if (!patrn.exec(s)) return false;
        return true;
    },
    //检验体重
    IsAvoirdupois: function (s) {
        var patrn = /^[1-9]{1}[0-9]{0,2}$/;
        var patrn2 = /^[1-9]{1}$/;
        var intPart = s.indexOf('.');
        var decPart = s.lastIndexOf('.');
        if (intPart == -1 && patrn.exec(s) && (s) >= 2 && (s) > 300) return false;
        return true;
    },
    //校验普通电话、传真号码：可以“+”开头，除数字外，可含有“-”
    IsTel: function (s) {
        var patrn = /^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$/;
        if (!patrn.exec(s)) return false;
        return true;
    },
    //校验手机号码：必须以数字开头
    IsMobile: function (s) {
        var patrn = /^(13[0-9]|15[012356789]|18[0236789]|14[57])[0-9]{8}$/;
        return patrn.test(s);
        // return (new RegExp(/^(130|131|132|133|134|135|136|137|138|139|150|152|153|157|158|156|159|180|187|188|189|183|182)\d{8}$/).test(s));
    },
    //校验地区代码
    isAreaCode: function (s) {
        var patrn = /^(\d){6}$/;
        if (!patrn.exec(s)) return false;
        return true;
    },
    //1-16个中文
    IsChinese: function (s) {
        var patrn = /^[\u4E00-\u9FA5]{1,16}$/;
        if (!patrn.exec(s)) return false;
        return true;
    },
    //校验邮政编码
    IsPostalCode: function (s) {
        var patrn = /^[1-9]{1}(\d){5}$/;
        if (!patrn.exec(s)) return false;
        return true;
    },
    //检查email邮箱
    IsEmail: function (str) {
        var reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
        //var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
        return reg.test(str);
    },
    //中英文数字下划线4-16个字符
    IsAccount: function (str) {
        var reg = /^[a-zA-Z0-9_\u4e00-\u9fa5]{2,16}$/;
        //var reg = /^[a-zA-Z0-9_]{6,16}$/;
        return reg.test(str);
    },
    //检查长度
    CheckLength: function checkLength(obj, maxlength) {
        if (obj.value.length > maxlength) {
            obj.value = obj.value.substring(0, maxlength);
        }
    }
}
//判断字符长度(一个汉字两个字符，其他一个字符)
function len(s) {
    var l = 0;
    var a = s.split("");
    for (var i = 0; i < a.length; i++) {
        if (a[i].charCodeAt(0) < 299) {
            l++;
        } else { l += 2; }

    }
    return l;
}

DaAn.Tips = function (options) {
    /// <summary>
    /// 提示消息
    /// </summary>
    /// <param name="options" type="Jquery">
    /// 1 type 提示类型 info 表示：提示信息 success 正确提示信息
    /// 2 time 显示时间 不传默认为3秒
    /// 3 content 提示信息
    ///</param>
    var defaults = {
        //        type: "info",
        lock: false,
        time: 3,
        content: ""
    };
    var setting = $.extend({}, defaults, options || {});
    if (setting.type == "success") {
        setting.content = "<span  class=\"upbox-uniline round colorGreen\"><em class=\"icon-succeed margin-r10\"></em>" + setting.content + "</span>";
        art.artDialog.tips(setting)
    } else if (setting.type == "load") {
        setting.content = "<span  class=\"upbox-uniline round colorGray\"><em class=\"icon-load margin-r10\"></em>" + setting.content + "</span>";
        art.artDialog.tips(setting).lock();
    } else {
        setting.content = "<span class=\"upbox-uniline colorOrange\"><em class=\"icon-point margin-r10\"></em>" + setting.content + "</span>";
        art.artDialog.tips(setting);
    }


    //artDialog.tips(setting).lock();
    //    if (typeof (setting.url) != "undefined") {
    //        setTimeout(function () { location.href = setting.url; }, 1500);
    //    }
}
DaAn.Tip = function (msg) {
    /// <summary>
    /// 提示消息
    /// </summary>
    /// <param name="msg" type="String">
    ///  消息内容
    ///</param>
    DaAn.Tips({ content: msg })
}
//(function ($) {
    //$.fn.Tips = $.Tips = DaAn.Tips(options);

    $.fn.Enter = function (callback) {
        $(this).bind("keydown", function (event) {
            if (event.keyCode == 13) {
                callback();
            }
        });
    }
//})(jQuery);

    DaAn.Login = function (returnurl) {
    
        if (returnurl != undefined || returnurl == "") {
            returnurl = "?returnurl=" + returnurl;
        } else {
            returnurl = "";
        }
        art.dialog.open("/circle/speedLoading.aspx" + returnurl,
         {
             width: "380px",
             height: "220px",
             title: ""
             //            ,close: function () {
             //                 location = location; 
             //            } 
         }).lock();
     
    }
        //(function ($) {
    DaAn.TipMsg = function (obj, msg, options) {
        /// <summary>
        /// 文本框验证样式设置
        /// </summary>
        var defaults = {
            //文字
            textElement: "em",
            textErrorClass: "colorRed",
            textSuccessClass: "colorGreen",
            //验证通过
            Success: false,
            //文本框
            inputErrorClass: "input-error",
            inputSuccessClass: "input-click",
            //图标
            icon: "span",
            iconErrorClass: "error-icon margin-l10",
            iconSuccessClass: "correct-icon margin-l10",
            ShowMessage: true,
            ShowSuccessMessage: false,
            ShowDefaultStyle: false
        };
        var setting = $.extend({}, defaults, options || {});
        msg = setting.ShowMessage == true ? msg : "";
        if (setting.ShowDefaultStyle) {
            $(obj).removeClass(setting.inputSuccessClass).removeClass(setting.inputErrorClass);
            $(obj).siblings(setting.textElement).eq(0).html("");
            $(obj).siblings(setting.icon).eq(0).removeClass();
            return;
        }
        if (setting.Success) {
            $(obj).removeClass(setting.inputErrorClass).addClass(setting.inputSuccessClass);
            msg = setting.ShowSuccessMessage == true ? msg : ""; 
            $(obj).siblings(setting.textElement).eq(0).attr("class", setting.textSuccessClass).html(msg);
            $(obj).siblings(setting.icon).eq(0).attr("class", setting.iconSuccessClass).show();
        } else {
            $(obj).removeClass(setting.inputSuccessClass).addClass(setting.inputErrorClass);
            $(obj).siblings(setting.textElement).eq(0).attr("class", setting.textErrorClass).html(msg);
            $(obj).siblings(setting.icon).eq(0).attr("class", setting.iconErrorClass).show();
        }

    }
//})(jQuery);

//var DaAnValidAll ={Email:false,Phone:false,Account:false,Idcard:false};


    DaAnValid = {
        Email: { Check: false, Value: "" },
        Phone: { Check: false, Value: "" },
        Account: { Check: false, Value: "" },
        Idcard: { Check: false, Value: "" },
        RealName: { Check: false, Value: "" },
        UserNo: { Check: false, Value: "" },
        HospitalName: { Check: false, Value: "" }
    };

    function loadimg(obj,options) {
        var html = "<img src='/images/icon/loading.gif'  width='16' height='16' style='margin-bottom:-3px; margin-left:8px;margin-right:5px;' /><em class='colorGray'>正在检测...<em>";
        var setting = $.extend({}, options || {}, {iconErrorClass:"",iconSuccessClass:""});
        DaAn.TipMsg(obj, html, setting);
    }
    DaAn.Validate = {
        Email: function (Obj, oldValue, required, options) {
            var newValue = $.trim($(Obj).val());
            if (required && newValue == "") {
                var setting = $.extend({}, options || {}, { ShowDefaultStyle: true });
                DaAn.TipMsg(Obj, "", setting);
                DaAnValid.Email.Check = true;
                return;
            }
            if (!DaAn.Regexp.IsEmail(newValue)) {
                DaAn.TipMsg(Obj, "请填写正确格式的电子邮箱", options);
                DaAnValid.Email.Check = false;
                return;
            }
            if ((oldValue == newValue && newValue != "") || (DaAnValid.Email.Value == newValue)) {
                DaAnValid.Email.Check = true;
                DaAnValid.Email.Value = newValue;
                var setting = $.extend({}, options || {}, { Success: true });
                DaAn.TipMsg(Obj, "恭喜，该邮箱可以使用", setting);
                return;
            }
            DaAn.Ajax("/Services/AjaxHandler.ashx?action=Account.Check", { "action": "Mail", "value": newValue }, function (result) {
                if (result == "true") {
                    var setting = $.extend({}, options || {}, { Success: true });
                    DaAn.TipMsg(Obj, "恭喜，邮箱可以使用", setting);
                    DaAnValid.Email.Check = true;
                    DaAnValid.Email.Value = newValue;
                    return;
                } else {
                    DaAn.TipMsg(Obj, "该邮箱已被注册，请换一个邮箱试试", options);
                    DaAnValid.Email.Check = false;
                    return;
                }
            }, { type: "post", before: loadimg(Obj, options) });
        },
        Account: function (Obj, oldValue, required, options) {
            var newValue = $.trim($(Obj).val());
            var vallen = len(newValue);
            if (DaAn.Regexp.IsAccount(newValue) && vallen >= 4 && vallen <= 16) {
                var setting = $.extend({}, options || {}, { Success: true });
                DaAn.TipMsg(Obj, "正确", setting);
                DaAnValid.Account.Check = true;
                return;
            }
            DaAn.TipMsg(Obj, "由4-16个字符组成，可以是中英文、数字和下划线", options);
            DaAnValid.Account.Check = false;
            return;
        },
        HospitalName: function (Obj, required, options) {
            var value = $.trim($(Obj).val());
            var setting = $.extend({}, options || {}, { Success: true });
            if (value.length != 0) {
                if (value.length > 30) {
                    DaAn.TipMsg(Obj, "名称长度不能大于30", options);
                    DaAnValid.HospitalName.Check = false;
                    return;
                } else {
                    DaAn.TipMsg(Obj, "", setting);
                    DaAnValid.HospitalName.Check = true;
                }
            } else { DaAnValid.HospitalName.Check = true; }
        },
        Phone: function (Obj, oldValue, required, options) {
            var newValue = $.trim($(Obj).val());
            if (required && newValue == "") {
                var setting = $.extend({}, options || {}, { ShowDefaultStyle: true });
                DaAn.TipMsg(Obj, "", setting);
                DaAnValid.Phone.Check = true;
                return;
            }
            if (!DaAn.Regexp.IsMobile(newValue)) {
                DaAn.TipMsg(Obj, "请填写正确格式的手机号码", options);
                DaAnValid.Phone.Check = false;
                return;
            }
            if ((oldValue == newValue && newValue != "") || (DaAnValid.Phone.Value == newValue)) {
                DaAnValid.Phone.Check = true;
                DaAnValid.Phone.Value = newValue;
                var setting = $.extend({}, options || {}, { Success: true });
                DaAn.TipMsg(Obj, "恭喜，手机号码可以使用", setting);
                return;
            }
            DaAn.Ajax("/Services/AjaxHandler.ashx?action=Account.Check", { "action": "Mobile", "value": newValue }, function (result) {
                if (result == "true") {
                    DaAnValid.Phone.Check = true;
                    DaAnValid.Phone.Value = newValue;
                    var setting = $.extend({}, options || {}, { Success: true });
                    DaAn.TipMsg(Obj, "恭喜，手机号码可以使用", setting);
                    return;
                } else {
                    DaAn.TipMsg(Obj, "该手机号码已被注册，请换一个手机号码试试", options);
                    DaAnValid.Phone.Check = false;
                    return;
                }
            }, { type: "post", before: loadimg(Obj, options) });
        },
        IdCard: function (Obj, oldValue, required, options) {
            var newValue = $.trim($(Obj).val());
            if (required && newValue == "") {
                var setting = $.extend({}, options || {}, { ShowDefaultStyle: true });
                DaAn.TipMsg(Obj, "", setting);
                DaAnValid.Idcard.Check = true;
                return;
            }
            var msg = DaAn.Regexp.IsIdCardNo(newValue);
            if (msg == false) {
                DaAn.TipMsg(Obj, "请输入真实正确的身份证号码", options);
                DaAnValid.Idcard.Check = false;
                return;
            }
            //            var msg = DaAn.Regexp.IsIdCardNo(newValue);
            //            if (msg != "验证通过!") {
            //                DaAn.TipMsg(Obj, msg, options);
            //                DaAnValid.Idcard.Check = false;
            //                return;
            //            }
            if ((oldValue == newValue && newValue != "") || (DaAnValid.Idcard.Value == newValue)) {
                DaAnValid.Idcard.Check = true;
                DaAnValid.Idcard.Value = newValue;
                var setting = $.extend({}, options || {}, { Success: true });
                DaAn.TipMsg(Obj, "正确", setting);
                return;
            }
            DaAn.Ajax("/Services/AjaxHandler.ashx?action=Account.Check", { "action": "IdCard", "value": newValue }, function (result) {
                if (result == "true") {
                    DaAnValid.Idcard.Check = true;
                    DaAnValid.Idcard.Value = newValue;
                    var setting = $.extend({}, options || {}, { Success: true });
                    DaAn.TipMsg(Obj, "正确", setting);
                    return;
                } else {
                    DaAn.TipMsg(Obj, "该身份证号码已被使用，请换一个试试", options);
                    DaAnValid.Idcard.Check = false;
                    return;
                }
            }, { type: "post", before: loadimg(Obj, options) });
        },
        RealName: function (Obj, required, options) {
            var newValue = $.trim($(Obj).val());
            if (required && newValue == "") {
                var setting = $.extend({}, options || {}, { ShowDefaultStyle: true });
                DaAn.TipMsg(Obj, "", setting);
                DaAnValid.RealName.Check = true;
                return;
            }
            if (DaAn.Regexp.IsChinese(newValue)) {
                var setting = $.extend({}, options || {}, { Success: true });
                DaAn.TipMsg(Obj, "正确", setting);
                DaAnValid.RealName.Check = true;
            } else {
                DaAn.TipMsg(Obj, "请输入1-16个中文", options);
                DaAnValid.RealName.Check = false;
            }
        },
        UserNo: function (Obj, oldValue, orgid, userId, required, options) {
            var newValue = $.trim($(Obj).val());
            if (required && newValue == "") {
                var setting = $.extend({}, options || {}, { ShowDefaultStyle: true });
                DaAn.TipMsg(Obj, "", setting);
                DaAnValid.UserNo.Check = true;
                return;
            }
            if ((oldValue == newValue && newValue != "") || (DaAnValid.UserNo.Value == newValue)) {
                DaAnValid.UserNo.Check = true;
                DaAnValid.UserNo.Value = newValue;
                var setting = $.extend({}, options || {}, { Success: true });
                DaAn.TipMsg(Obj, "恭喜，该工号可以使用", setting);
                return;
            }
            DaAn.Ajax("/Services/AjaxHandler.ashx?action=Organization.CheckUserNo",
        { orgid: orgid, userId: userId, userNo: newValue },
         function (result) {
             if (result != "1002") {
                 var setting = $.extend({}, options || {}, { Success: true });
                 DaAn.TipMsg(Obj, "恭喜，该工号可以使用", setting);
                 DaAnValid.UserNo.Check = true;
                 DaAnValid.UserNo.Value = newValue;
                 return;
             } else {
                 DaAn.TipMsg(Obj, "该工号已使用，请换一个工号试试", options);
                 DaAnValid.UserNo.Check = false;
                 return;
             }
         }, { type: "post", before: loadimg(Obj, options) });
        }
    };

    $(document).ready(function () {
        $('textarea[maxContent]').each(function () {
            $(this).inputlimiter({
                limit: $(this).attr('maxContent'),
                remText: '您还可以输入<em class="colorGreen">%n</em>个字符',
                remFullText: '您还可以输入<font color="red">%n</font>个字符',
                limitText: ''
            });
        });
        //禁止输入空格
        $("input[trims]").keydown(function (event) {
            if (event.keyCode == 32) {
                return false;
            }
            //            var value = $(this).val();
            //            value = value.replace(/(^\s*)|(\s*$)/g, '');
            //            $(this).val(value);
        });
        //文本框获得焦点变绿色
        $("input[focus]").focus(function () {
            $(this).addClass("input-click");
        }).blur(function () {
            $(this).removeClass("input-click");
        });
        $("textarea").focus(function () {
            $(this).css("border", "1px solid green");
        }).blur(function () {
            $(this).css("border", "1px solid #CCCCCC");
        });
    });


    function checkDate(date) {
        return true;
    } 